// pages/contact/contact.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputShowed: false,
    inputVal: "",
    letterList: [],
    toView: '',
    list: [],
    barHeight: wx.getSystemInfoSync().statusBarHeight,
    isSearching: false,
    searchResult: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    // 模拟网络请求
    wx.request({
      url: 'http://127.0.0.1:3000/userData',
      success (res) {
        console.log('获取联系人数据成功:', res.data);
        let data = res.data || [];
        that.processContactData(data);
      },
      fail() {
        console.log('使用本地示例数据');
        that.processContactData(that.createSampleData());
      }
    })
  },

  // 处理联系人数据，按字母分组
  processContactData(data) {
    console.log('原始数据:', data);
    
    // 检查数据是否为数组
    if (!Array.isArray(data)) {
      console.error('数据格式错误，使用示例数据');
      data = this.createSampleData();
    }
    
    // 确定使用哪个字段作为名称
    let nameField = 'name';
    if (data.length > 0) {
      if (!data[0].name && data[0].username) nameField = 'username';
      else if (!data[0].name && data[0].nickname) nameField = 'nickname';
      else if (!data[0].name && data[0].fullName) nameField = 'fullName';
    }
    
    // 创建26个字母分组
    let contactList = [];
    let letterList = [];
    
    for (let i = 0; i < 26; i++) {
      let letter = String.fromCharCode(65 + i);
      let group = {
        letter: letter,
        data: []
      };
      
      // 按首字母分组
      data.forEach(item => {
        let name = item[nameField] || '';
        if (typeof name !== 'string') name = String(name);
        let firstLetter = this.getFirstLetter(name);
        
        if (firstLetter === letter) {
          group.data.push({...item, [nameField]: name});
        }
      });
      
      // 只添加有数据的分组
      if (group.data.length > 0) {
        contactList.push(group);
        letterList.push(letter);
      }
    }
    
    // 添加星标联系人分组
    let starGroup = {
      letter: "★",
      data: data.filter(item => item.isStar)
    };
    
    if (starGroup.data.length > 0) {
      contactList.unshift(starGroup);
      letterList.unshift("★");
    }
    
    // 添加#分组（非字母开头的联系人）
    let otherGroup = {
      letter: "#",
      data: []
    };
    
    data.forEach(item => {
      let name = item[nameField] || '';
      if (typeof name !== 'string') name = String(name);
      let firstLetter = this.getFirstLetter(name);
      
      if (!/[A-Z★]/.test(firstLetter)) {
        otherGroup.data.push({...item, [nameField]: name});
      }
    });
    
    if (otherGroup.data.length > 0) {
      contactList.push(otherGroup);
      letterList.push("#");
    }
    
    console.log('处理后的联系人列表:', contactList);
    
    this.setData({
      list: contactList,
      letterList: letterList,
      allContacts: data,
      nameField: nameField
    });
  },
  
  // 获取中文首字母或英文首字母
  getFirstLetter(name) {
    if (!name) return '#';
    
    let firstChar = name.charAt(0).toUpperCase();
    // 检查是否为字母
    if (/[A-Z]/.test(firstChar)) {
      return firstChar;
    }
    
    // 简单处理中文（实际项目中可使用pinyin库）
    const pinyinMap = {
      '阿': 'A', '八': 'B', '擦': 'C', '搭': 'D', '鹅': 'E',
      '发': 'F', '噶': 'G', '哈': 'H', '衣': 'Y', '鸡': 'J',
      '卡': 'K', '拉': 'L', '妈': 'M', '拿': 'N', '哦': 'O',
      '啪': 'P', '期': 'Q', '日': 'R', '撒': 'S', '他': 'T',
      '屋': 'W', '哇': 'W', '西': 'X', '呀': 'Y', '咋': 'Z'
    };
    
    return pinyinMap[firstChar] || '#';
  },
  
  // 创建示例数据
  createSampleData() {
    return [
      { id: 1, name: '张三', avatar: '/assets/images/profile/刘邦.jpg', isStar: true },
      { id: 2, name: '李四', avatar: '/assets/images/profile/李信.jpg' },
      { id: 3, name: '王五', avatar: '/assets/images/profile/项羽.jpg' },
      { id: 4, name: '赵六', avatar: '/assets/images/profile/张良.jpg' },
      { id: 5, name: '钱七', avatar: '/assets/images/profile/虞姬.jpg', isStar: true },
      { id: 6, name: '孙八', avatar: '/assets/images/profile/白起.jpg' },
      { id: 7, name: '周九', avatar: '/assets/images/profile/嬴政.jpg' },
      { id: 8, name: '吴十', avatar: '/assets/images/profile/韩信.jpg' },
      { id: 9, name: '123测试', avatar: '/assets/images/profile/高渐离.jpg' },
      { id: 10, name: 'Apple', avatar: '/assets/images/profile/蒙恬.jpg' },
      { id: 11, name: 'Banana', avatar: '/assets/images/profile/蒙恬.jpg' },
      { id: 12, name: '橙子', avatar: '/assets/images/profile/蒙恬.jpg' },
      { id: 13, name: '葡萄', avatar: '/assets/images/profile/蒙恬.jpg' },
      { id: 14, name: '西瓜', avatar: '/assets/images/profile/蒙恬.jpg' }
    ];
  },
  
  // 点击字母导航
  letterTap(e) {
    const id = e.currentTarget.dataset.id;
    this.setData({
      toView: id,
      scrollTopId: id
    });
  },
  
  // 搜索框相关函数
  showInput() {
    this.setData({
      inputShowed: true,
      isSearching: true
    });
  },
  hideInput() {
    this.setData({
      inputVal: "",
      inputShowed: false,
      isSearching: false,
      searchResult: []
    });
  },
  clearInput() {
    this.setData({
      inputVal: "",
      searchResult: []
    });
  },
  inputTyping(e) {
    const value = e.detail.value.trim();
    this.setData({ inputVal: value });
    
    if (!value) {
      this.setData({ searchResult: [] });
      return;
    }
    
    // 搜索逻辑
    const { allContacts, nameField } = this.data;
    const result = allContacts.filter(item => 
      item[nameField].toLowerCase().includes(value.toLowerCase())
    );
    
    this.setData({ searchResult: result });
  },
  
  // 点击联系人
  tapContact(e) {
    const contact = e.currentTarget.dataset.contact;
    // 使用toast提示而不是导航，避免页面不存在的错误
    wx.showToast({
      title: `联系人: ${contact.name || '未知'}`,
      icon: 'none',
      duration: 1500
    });
    
    // 如果确认contactDetail页面存在，可以使用以下代码导航
    // wx.navigateTo({
    //   url: `/pages/contactDetail/contactDetail?id=${contact.id}`
    // });
  },
  
  // 点击功能入口
  tapFunction(e) {
    const type = e.currentTarget.dataset.type;
    const typeNameMap = {
      'newFriend': '新的朋友',
      'groupChat': '群聊',
      'tags': '标签',
      'official': '公众号'
    };
    
    // 使用toast提示而不是导航，避免页面不存在的错误
    wx.showToast({
      title: `点击了${typeNameMap[type] || type}`,
      icon: 'none',
      duration: 1500
    });
    
    // 如果确认相应页面存在，可以使用以下代码导航
    // switch(type) {
    //   case 'newFriend':
    //     wx.navigateTo({ url: '/pages/newFriend/newFriend' });
    //     break;
    //   case 'groupChat':
    //     wx.navigateTo({ url: '/pages/groupChat/groupChat' });
    //     break;
    //   case 'tags':
    //     wx.navigateTo({ url: '/pages/tags/tags' });
    //     break;
    //   case 'official':
    //     wx.navigateTo({ url: '/pages/official/official' });
    //     break;
    // }
  }
})